package net.tv90.auth.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.tv90.auth.model.AccountToken;
import net.tv90.auth.model.LoginStatus;
import net.tv90.auth.service.VerifyService;
import net.tv90.auth.utils.TokenUtils;
import net.tv90.auth.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class VerifyServiceImpl implements VerifyService {

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    UserUtils userUtils;

    /**
     * 这个方法只走缓存
     */
    @Override
    public Integer checkVerified(String token, String baseUrl) {
        Integer role;
        try {
            AccountToken accountToken;
            try {
                accountToken = tokenUtils.parseToken(token);
            } catch (IllegalArgumentException e) {
                log.warn("来自{}的token:{}不合法，请求失败", baseUrl, token);
                return null;
            }
            String username = accountToken.getUsername();
            LoginStatus loginStatus = userUtils.getUserLoginStatus(username);
            String verifyToken = (loginStatus == null) ? null : loginStatus.getToken();
            role = (loginStatus == null) ? null : loginStatus.getRole();
            if (verifyToken == null) {
                log.warn("来自{}的token:{}已过期，请求失败", baseUrl, token);
                return null;
            }
            if (!verifyToken.equals(token)) {
                log.warn("来自{}的token:{}已过期（用户名{}）token校验失败，请求失败", baseUrl, username, token);
                return null;
            }
        } catch (Exception e) {
            return null;
        }
        log.info("来自{}的请求token:{}校验成功，权限为{}", baseUrl, token, role);
        return role;
    }
}
